package com.exonline.backstage.controller.pay;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.config.AlipayConfig;
import com.exonline.backstage.entity.Courses;
import com.exonline.backstage.entity.Student;
import com.exonline.commons.dao.DaoImpl;
import com.exonline.commons.dao.IDao;
import com.exonline.commons.utils.TokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 支付宝沙箱支付接口
 * @author YUKI
 * @date 2024/12/5
 */
@WebServlet("/admin/pay")
public class PayServlet extends HttpServlet {
    ObjectMapper mapper = new ObjectMapper();
    IDao<Courses> dao = new DaoImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String info = req.getParameter("info");
        String cid = TokenUtil.getCid(info);
        String sid = TokenUtil.getSid(info);

        String WIDsubject = "";
        String WIDtotalAmount = null;
        String body = "";
        String cname = "";

        String sname = "";
        try {
            Courses courses = dao.queryForObject("select * from courses where id = ?", new BeanHandler<>(Courses.class), cid);
            cname = courses.getCname();
            sname = dao.queryForObject("select * from student where id = ?", new BeanHandler<>(Student.class), sid).getSname();
            WIDsubject = courses.getCname();
            WIDtotalAmount = courses.getCprice();

        } catch (SQLException e) {
            throw new RuntimeException("用户支付时参数错误或不存在此课程"+e.getMessage(),e);
        }


//        //解析json支付信息
//        Map<String,Object> payInfo = mapper.readValue(req.getInputStream(), Map.class);
//        String WIDsubject = payInfo.get("WIDsubject").toString();
//        String wiDtotalAmount = payInfo.get("WIDtotal_amount").toString();
//        String wiDbody = payInfo.get("WIDbody").toString();

        String WIDout_trade_no = IdUtil.randomUUID();

        if(WIDout_trade_no!=null){
            // 商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = new String(WIDout_trade_no);
            // 订单名称，必填
            String subject = new String(WIDsubject);
            System.out.println(subject);
            // 付款金额，必填
            String total_amount=new String(WIDtotalAmount);
            // 商品描述，可空
            if (req.getParameter("widbody")!=null) {
                body = new String(req.getParameter("widbody"));
            }

            // 超时时间 可空
            String timeout_express="10m";
            // 销售产品码 必填
//    String product_code="QUICK_WAP_WAY";
            String product_code="FAST_INSTANT_TRADE_PAY";
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
            AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
            AlipayTradePagePayRequest alipay_page_request=new AlipayTradePagePayRequest();
            // 封装请求支付信息
            AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
            AlipayTradePagePayModel page_model=new AlipayTradePagePayModel();

            page_model.setOutTradeNo(out_trade_no);
            page_model.setSubject(subject);
            page_model.setTotalAmount(total_amount);
            page_model.setBody(body);
            page_model.setTimeoutExpress(timeout_express);
            page_model.setProductCode(product_code);
            alipay_page_request.setBizModel(page_model);

            alipay_page_request.setNotifyUrl(AlipayConfig.notify_url);
            alipay_page_request.setReturnUrl(AlipayConfig.return_url);


            model.setOutTradeNo(out_trade_no);
            model.setSubject(subject);
            model.setTotalAmount(total_amount);
            model.setBody(body);
            model.setTimeoutExpress(timeout_express);
            model.setProductCode(product_code);
            alipay_request.setBizModel(model);
            // 设置异步通知地址
            alipay_request.setNotifyUrl(AlipayConfig.notify_url);
            // 设置同步地址
            alipay_request.setReturnUrl(AlipayConfig.return_url);

            // form表单生产
            String form = "";
            try {
                // 调用SDK生成表单
                form = client.pageExecute(alipay_page_request).getBody();
                resp.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
                resp.getWriter().write(form);//直接将完整的表单html输出到页面
                resp.getWriter().flush();
                resp.getWriter().close();
            } catch (AlipayApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                dao.updateWithTransaction("INSERT INTO orders(id,cid,sid,status) VALUES(?,?,?,?)", WIDout_trade_no,cid, sid,0);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
